<?php
//by willson 105328468@qq.com 2014/10/13
//member module interface

class member extends core {
	private $member_mod;
	private $order_mod;
	private $withdraw_mod;
	private $commission_mod;

	public function __construct() {
		parent::__construct();
		$this->member_mod = m("member");
		$this->order_mod = m("order");
		$this->withdraw_mod = m("withdraw");
		$this->commission_mod = m("commission");
	}

	//首页会员首页接口，在登录时数据已经取到
	public function index() {
		$sign = (isset($_GET['sign']) && trim($_GET['sign'])) ? trim($_GET['sign']) : '';
		$not_pay = $not_shipping = $not_confirm = $not_comment = $notify = 0; //$notify供微信端用
		$member = null;
		if ($this->member_id) {
			if ($sign) {
				$sql = "SELECT count(*) FROM {$this->tbp}member WHERE sign='{$sign}' AND id='{$this->member_id}'";
				$exists = intval($this->db->get_var($sql));
				if (!$exists) error('该账号已在其他设备登录', -9);
			}
			$not_pay = $this->_get_one_status_order(0, $this->member_id);
			$not_shipping = $this->_get_one_status_order(1, $this->member_id);
			$not_confirm = $this->_get_one_status_order(2, $this->member_id);
			$not_comment = $this->_get_one_status_order(3, $this->member_id);
			$sql = "SELECT count(*) FROM {$this->tbp}message WHERE member_id='{$this->member_id}' AND readed=0";
			$notify = intval($this->db->get_var($sql));
			//获取会员所有信息
			$sql = "SELECT * FROM {$this->tbp}member WHERE id='{$this->member_id}'";
			$member = $this->db->get_row($sql);
			if ($member) {
				$member->total_price = strval($member->money+$member->commission);
				//获取当前等级的下个等级
				$score = 0;
				$sql = "SELECT score FROM {$this->tbp}member_grade WHERE status=1 AND id>'{$member->grade_id}' ORDER BY sort ASC, id ASC";
				$row = $this->db->get_row($sql);
				if ($row) $score = intval($row->score);
				if ($score==0) {
					$sql = "SELECT score FROM {$this->tbp}member_grade WHERE id='{$member->grade_id}'";
					$score = intval($this->db->get_var($sql));
				}
				$member->next_score = "{$score}";
				$sql = "SELECT * FROM {$this->tbp}member_grade WHERE id='{$member->grade_id}'";
				$grade = $this->db->get_row($sql);
				$member->grade = $grade;
			}
			$member = add_domain_deep($member, array('avatar', 'pic'));
			$_SESSION['member'] = $member;
		}
		//获取购物车总数
		$sql = "SELECT IFNULL(SUM(quantity),0) FROM {$this->tbp}cart WHERE 1";
		if ($this->member_id>0) {
			$sql .= " AND (member_id='{$this->member_id}' OR session_id='".session_id()."')";
		} else {
			$sql .= " AND session_id='".session_id()."'";
		}
		$cart_total = intval($this->db->get_var($sql));
		$coupon_count = $this->_get_coupon_count();

		success(array("member_id" => intval($this->member_id),
			"cart_total" => $cart_total,
			"coupon_count" => $coupon_count,
			"not_pay" => $not_pay,
			"not_shipping" => $not_shipping,
			"not_confirm" => $not_confirm,
			"not_comment" => $not_comment,
			"notify" => $notify,
			"member" => $member,
		));
	}

	//优惠券总数
	private function _get_coupon_count() {
		$sql = "SELECT count(*) FROM {$this->tbp}coupon_sn WHERE status='1' AND member_id='{$this->member_id}' AND member_id>'0'";
		//echo $sql;
		$num = intval($this->db->get_var($sql));
		return $num;
	}

	private function _get_one_status_order($status, $member_id) {
		$sql = "SELECT count(*) FROM {$this->tbp}order WHERE status='{$status}' AND member_id='{$member_id}' AND readed=1";
		$num = intval($this->db->get_var($sql));
		return $num;
	}

	//个人资料
	public function edit() {
		//微信JSSDK，在微信端读取
		if ($this->is_weixin()) {
			$url = '';
			if (isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"])=="xmlhttprequest") {
				$url = "http://".$_SERVER['HTTP_HOST']."/wap.php";
			}
			require_once(FRAMEWORK_PATH . '/class/wxapi/config.php');
			require_once(FRAMEWORK_PATH . '/class/wxapi/jssdk.php');
			$weixin_jssdk = new JSSDK(WX_APPID, WX_SECRET);
			$weixin_sign_package = $weixin_jssdk->getSignPackage($url);
			$this->smarty->assign('weixin_sign_package', $weixin_sign_package);
		}
		success('ok');
	}

	//产品浏览历史
	public function goods_history() {
		$offset = (isset($_GET['offset']) && intval($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && intval($_GET['pagesize'])) ? intval($_GET['pagesize']) : 8;
		$sql = "SELECT g.* FROM {$this->tbp}member_goods_history h LEFT JOIN {$this->tbp}goods g ON g.id=h.goods_id
			WHERE member_id='{$this->member_id}' ORDER BY h.id DESC LIMIT {$offset}, {$pagesize}";
		$rs = $this->db->get_results($sql);
		$rs = add_domain_deep($rs, array("pic"));
		success($rs);
	}

	//余额明细
	public function money_history() {
		$offset = (isset($_GET['offset']) && trim($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && trim($_GET['pagesize'])) ? intval($_GET['pagesize']) : 12;
		$sql = "SELECT * FROM {$this->tbp}member_money_history WHERE member_id='{$this->member_id}' ORDER BY id DESC LIMIT {$offset},{$pagesize}";
		$rs = $this->db->get_results($sql);
		if ($rs) {
			foreach ($rs as $k => $g) {
				$rs[$k]->add_time = date("Y-m-d H:i:s", $g->add_time);
			}
		}
		success($rs);
	}

	//收入明细
	public function commission_history() {
		$offset = (isset($_GET['offset']) && trim($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && trim($_GET['pagesize'])) ? intval($_GET['pagesize']) : 12;
		$sql = "SELECT * FROM {$this->tbp}member_commission WHERE member_id='{$this->member_id}' ORDER BY id DESC LIMIT {$offset},{$pagesize}";
		$rs = $this->db->get_results($sql);
		if ($rs) {
			foreach ($rs as $k => $g) {
				$rs[$k]->status_name = $this->commission_mod->status_name($g->status);
				$rs[$k]->add_time = date("Y-m-d H:i:s", $g->add_time);
			}
		}
		success($rs);
	}

	//提现历史
	public function withdraw_history() {
		$offset = (isset($_GET['offset']) && trim($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && trim($_GET['pagesize'])) ? intval($_GET['pagesize']) : 15;
		$sql = "SELECT * FROM {$this->tbp}withdraw WHERE member_id='{$this->member_id}' ORDER BY id DESC LIMIT {$offset}, {$pagesize}";
		$rs = $this->db->get_results($sql);
		if ($rs) {
			foreach ($rs as $k=>$g) {
				$rs[$k]->title = '申请提现';
				$rs[$k]->status_name = $this->withdraw_mod->status_name($g->status);
				$rs[$k]->add_time = date('Y-m-d H:i:s', $g->add_time);
			}
		}
		success($rs);
	}

	//签到明细
	public function sign_history() {
		$offset = (isset($_GET['offset']) && trim($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && trim($_GET['pagesize'])) ? intval($_GET['pagesize']) : 12;
		$sql = "SELECT * FROM {$this->tbp}member_sign_history WHERE member_id='{$this->member_id}' ORDER BY id DESC LIMIT {$offset},{$pagesize}";
		$rs = $this->db->get_results($sql);
		if ($rs) {
			foreach ($rs as $k => $g) {
				$rs[$k]->add_time = date("Y-m-d H:i:s", $g->add_time);
			}
		}
		success($rs);
	}

	//积分使用明细
	public function integral_history() {
		$offset = (isset($_GET['offset']) && trim($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && trim($_GET['pagesize'])) ? intval($_GET['pagesize']) : 12;
		$sql = "SELECT * FROM {$this->tbp}member_integral_history WHERE member_id='{$this->member_id}' ORDER BY id DESC LIMIT {$offset},{$pagesize}";
		$rs = $this->db->get_results($sql);
		if ($rs) {
			foreach ($rs as $k => $g) {
				$rs[$k]->add_time = date("Y-m-d H:i:s", $g->add_time);
			}
		}
		success($rs);
	}

	//消费明细，读取订单，1已支付，2已发货，3完成（已收货），4完成（已评价）
	public function order_history() {
        if (!$this->member_id) script('请先登录账号', 'wap.php?tpl=login');
		$now = strtotime(date('Y-m-d'));
		$firstYear = date('Y', strtotime('-1 year'));
		$orders = SQL::share('order o')
			->left('service_city sc', 'o.city=sc.city_id')
			->where("o.member_id='{$this->member_id}' AND o.status>0")->find('o.id, o.month, o.status, sc.end_day');
		$years = array();
		//echo json_encode($orders);exit;
		for ($i=0; $i<3; $i++) {
			$y = array();
			for ($j=1; $j<=12; $j++) {
				$d = strtotime(($firstYear+$i)."-{$j}-".date('j'));
				$future = ($now<$d) ? 1 : 0;
				$date = date('Y-m', $d);
				$year = date('Y', $d);
				$data = new stdClass();
				$data->year = $year;
				$data->date = date('Ym', $d);
				$data->order_id = 0;
				$data->future = $future;
				$data->status = 0;
				if ($orders) {
					foreach ($orders as $k=>$g) {
						$data->future = ($now<$d || ($now==$d && $now<strtotime(date('Y-m-',$now).$g->end_day))) ? 1 : 0;
						if (stripos(",{$g->month},", ",{$date},")!==false) {
							$data->order_id = intval($g->id);
							$data->status = intval($g->status);
							break;
						}
					}
				}
				$y[] = $data;
			}
			$years[] = $y;
		}
//var_dump($years);exit();
        //增加PC需要的内容
        if (!isMobile()){
            //头像
            $sql = "SELECT avatar FROM {$this->tbp}member WHERE id='{$this->member_id}'";
            $avatar = $this->db->get_row($sql);
            //名称
            $sql = "SELECT nick_name FROM {$this->tbp}member WHERE id='{$this->member_id}'";
            $nick_name = $this->db->get_row($sql);
            // var_dump($rs);exit();
            success(array('years'=>$years, 'avatar'=>$avatar , 'nick_name'=>$nick_name));
        }else{
            success($years);
        }

	}

	//我的余额
    public function money(){
		$sql = "SELECT money FROM {$this->tbp}member WHERE id='{$this->member_id}'";
		$money = floatval($this->db->get_var($sql));
	    success($money);
    }

	//我的二维码
	public function code() {
		if ($this->member_id>0) {
			include_once(FRAMEWORK_PATH . "/class/phpqrcode/phpqrcode.php");
			$url = urldecode("{$this->domain}/wap.php?app=member&act=detail&invite_code=".$_SESSION['member']->invite_code);
			QRcode::png($url);
		}
		exit;
	}

	//首页会员首页获取即时的收入
	public function total_income() {
		$sql = "SELECT total_income FROM {$this->tbp}shop WHERE member_id='{$this->member_id}'";
		$total_income = floatval($this->db->get_var($sql));
		success($total_income);
	}

	//签到
	public function sign() {
		if (IS_POST) {
			if ($this->member_id<=0) error('请登录', -100);
			$sql = "SELECT count(*) FROM {$this->tbp}member_sign WHERE member_id='{$this->member_id}' AND add_time>'".strtotime(date("Y-m-d"))."'";
			//今天还没签到
			if (intval($this->db->get_var($sql)) == 0) {
				$every_score = isset($this->configs['sign_add_score']) ? intval($this->configs['sign_add_score']) : 2; //每次签到积分
				$continue_time = isset($this->configs['sign_continue_time']) ? intval($this->configs['sign_continue_time']) : 5; //连续次数临界点
				$continue_multiple = isset($this->configs['sign_continue_multiple']) ? intval($this->configs['sign_continue_multiple']) : 10; //超过临界点后的倍数
				$birthday_multiple = isset($this->configs['sign_birthday_multiple']) ? intval($this->configs['sign_birthday_multiple']) : 10; //生日的倍数
				$score = 0;
				$sql = "SELECT times, add_time FROM {$this->tbp}member_sign WHERE member_id='{$this->member_id}'";
				$row = $this->db->get_row($sql);
				if (!$row) { //第一次签到
					$score = $every_score;
					$sql = "INSERT INTO {$this->tbp}member_sign(member_id, times, add_time) VALUES('{$this->member_id}', '1', '".time()."')";
				} else {
					$times = intval($row->times);
					$add_time = $row->add_time;
					if (date('Y-m-d', $add_time)==date('Y-m-d', time()-60*60*24)) { //连续签到
						if ($times<$continue_time) { //连续签到5次之前，每次增加1倍
							$score = ($times+1) * $every_score;
						} else { //连续签到5次后开始每次10倍
							$score = ($times-$continue_time+1) * $continue_multiple;
						}
						$sql = "UPDATE {$this->tbp}member_sign SET times=times+1, add_time='".time()."' WHERE member_id='{$this->member_id}'";
					} else { //重新签到
						$score = $every_score;
						$sql = "UPDATE {$this->tbp}member_sign SET times=1, add_time='".time()."' WHERE member_id='{$this->member_id}'";
					}
				}
				$this->db->query($sql);
				$memo = '每日签到积分';
				//生日当天10倍
				if ((time()-$_SESSION['member']->reg_time)>=7*60*60*24 && //注册超过7天
					$_SESSION['member']->birth_month==intval(date('m')) && $_SESSION['member']->birth_day==intval(date('d'))) {
					$memo .= "(生日{$birthday_multiple}倍积分)";
					$score = $score * $birthday_multiple;
				}
				//插入签到历史
				$sql = "INSERT INTO {$this->tbp}member_sign_history(member_id, score, memo, add_time)
					VALUES('{$this->member_id}', '{$score}', '{$memo}', '".time()."')";
				$this->db->query($sql);
				//插入积分历史
				$sql = "INSERT INTO {$this->tbp}member_integral_history(member_id, integral, memo, add_time)
					VALUES('{$this->member_id}', '{$score}', '{$memo}', '".time()."')";
				$this->db->query($sql);
				//更新会员积分
				$sql = "UPDATE {$this->tbp}member SET integral=integral+{$score} WHERE id='{$this->member_id}'";
				$this->db->query($sql);
				$sql = "SELECT integral FROM {$this->tbp}member WHERE id='{$this->member_id}'";
				$integral = intval($this->db->get_var($sql));
				$_SESSION['member']->integral = $integral;
				success('ok');
			} else {
				error('今天已签到');
			}
		} else {
			//获取当前月的所有签到日期
			$days = array();
			$sql = "SELECT add_time FROM {$this->tbp}member_sign_history
				WHERE member_id='{$this->member_id}' AND add_time>='".strtotime(date('Y-m-1'))."' AND add_time<='".strtotime(date('Y-m-d 23:59:59'))."'";
			$rs = $this->db->get_results($sql);
			if ($rs) {
				foreach ($rs as $k=>$g) {
					$days[] = date('Y-m-d', $g->add_time);
				}
			}
			//已连续签到天数
			$times = 0;
			$sql = "SELECT times FROM {$this->tbp}member_sign WHERE member_id='{$this->member_id}'";
			$row = $this->db->get_row($sql);
			if ($row) $times = intval($row->times);
			//今天是否已签到
			$signed = 0;
			$sql = "SELECT add_time FROM {$this->tbp}member_sign_history WHERE member_id='{$this->member_id}' ORDER BY add_time DESC LIMIT 1";
			$row = $this->db->get_row($sql);
			if ($row) {
				$add_time = $row->add_time;
				if (strtotime(date('Y-m-d', $add_time))>=strtotime(date('Y-m-d', time()))) $signed = 1;
			}
			success(array('signed'=>$signed, 'times'=>$times, 'days'=>$days));
		}
	}

	//上传头像
	public function avatar() {
		$avatar = upload_one_file('avatar', 'avatar');
		if (!$avatar) error('头像上传失败');
		$sql = "UPDATE {$this->tbp}member SET avatar='{$avatar}' WHERE id='{$this->member_id}'";
		$this->db->query($sql);
		$avatar = add_domain($avatar);
		//$avatar .= "!logo"; //logo缩略图 by willson 2015/9/6
		$_SESSION['member']->avatar = $avatar;
		success($avatar);
	}

	//微信端上传头像
	public function wx_avatar() {
		$image_id = (isset($_POST['avatar']) && trim($_POST['avatar'])) ? trim($_POST['avatar']) : '';
		$avatar = '';
		if ($image_id!='') {
			//下载微信图片
			require_once(FRAMEWORK_PATH . '/class/wxapi/config.php');
			$wxapi = new wechatCallbackAPI();
			$json = $wxapi->access_token();
			$access_token = $json['access_token'];
			$url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$access_token}&media_id={$image_id}";
			$data = $wxapi->downloadFile($url);
			//$avatar = upload_obj_file($data, 'avatar', 'body', false); //保存在本地
			$avatar = upload_obj_file($data, 'avatar', 'body'); //上传到又拍云
		}
		if (!$avatar) error('头像上传失败');
		$sql = "UPDATE {$this->tbp}member SET avatar='{$avatar}' WHERE id='{$this->member_id}'";
		$this->db->query($sql);
		$avatar = add_domain($avatar);
		$_SESSION['member']->avatar = $avatar;
		success($avatar);
	}

	//修改个人资料
	public function edit_info() {
	    $name = $this->request->post('nick_name');
	    if (!$name) error('名称不能为空');

        $sql = "SELECT count(*) FROM {$this->tbp}member WHERE name='{$name}' AND id<>'{$this->member_id}'";
        $exists = intval($this->db->get_var($sql));
        if ($exists > 0) {
            error("名称已经存在");
        }

		$fields = array("real_name", "nick_name", "mobile", "qq", "weixin", "name", "email", "address",
			"birth_year", "birth_month", "birth_day", "avatar", "sex");
		$set_sql = "";
		foreach ($fields as $field) {
			if (isset($_POST[$field])) {
				$value = trim($_POST[$field]);
				if ($set_sql) {
					$set_sql .= ", `{$field}`='{$value}'";
				} else {
					$set_sql = "`{$field}`='{$value}'";
				}
				$_SESSION['member']->$field = $value;
			}
		}
		if ($set_sql) {
			$sql = "UPDATE {$this->tbp}member SET {$set_sql} WHERE id='{$this->member_id}'";
			//echo $sql;
			$this->db->query($sql);
		}
		//加入以下代码，会导致shop_id丢失
		//12/30
		$this->_reload_session_info();
		$sql = "SELECT * FROM {$this->tbp}member WHERE id='{$this->member_id}'";
		$row = $this->db->get_row($sql);
		success($row);
	}

	//PC显示反馈页面
    public function feed() {
        if (!$this->member_id) script('请先登录账号', 'wap.php?tpl=login');
        //头像
        $sql = "SELECT avatar FROM {$this->tbp}member WHERE id='{$this->member_id}'";
        $avatar = $this->db->get_row($sql);
        //名称
        $sql = "SELECT nick_name FROM {$this->tbp}member WHERE id='{$this->member_id}'";
        $nick_name = $this->db->get_row($sql);
        // var_dump($rs);exit();
        success(array('avatar'=>$avatar , 'nick_name'=>$nick_name));
    }



	//发送反馈
	public function feedback() {
		$type_id = (isset($_POST['type_id']) && intval($_POST['type_id'])) ? intval($_POST['type_id']) : 0;
		$name = (isset($_POST['name']) && trim($_POST['name'])) ? trim($_POST['name']) : '';
		$mobile = (isset($_POST['mobile']) && trim($_POST['mobile'])) ? trim($_POST['mobile']) : '';
		$content = (isset($_POST['content']) && trim($_POST['content'])) ? trim($_POST['content']) : '';

        $sql = "INSERT INTO {$this->tbp}feedback (member_id, name, mobile, content, add_time, ip, type_id)
        VALUES ('{$this->member_id}', '{$name}', '{$mobile}', '{$content}', '".time()."', '".ip()."', '{$type_id}')";
        $this->db->query($sql);
        success('ok');

	}

	//判断密码
	public function check_password() {
		$password = (isset($_POST['password']) && trim($_POST['password'])) ? trim($_POST['password']) : '';
		if ($password == '') error('密码不能为空');
		$sql = "SELECT password, salt FROM {$this->tbp}member WHERE id='{$this->member_id}'";
		$member = $this->db->get_row($sql);
		if ($member) {
			if ($member->password==crypt_password($password, $member->salt)) success('ok');
		}
		error('密码错误');
	}

	//修改密码
	public function password() {
		$origin_password = (isset($_POST['origin_password']) && trim($_POST['origin_password'])) ? trim($_POST['origin_password']) : '';
		$new_password = (isset($_POST['new_password']) && trim($_POST['new_password'])) ? trim($_POST['new_password']) : '';
		if ($new_password == '') error('密码不能为空');
		$sql = "SELECT password, salt FROM {$this->tbp}member WHERE id='{$this->member_id}'";
		$member = $this->db->get_row($sql);
		if ($member) {
			if ($member->password!=crypt_password($origin_password, $member->salt)) error('旧密码错误');
			$salt = rand(100000,999999);
			$crypt_password = md5(md5($new_password).$salt);
			$sql = "UPDATE {$this->tbp}member SET password='{$crypt_password}', origin_password='{$new_password}', salt='{$salt}' WHERE id='{$this->member_id}'";
			$this->db->query($sql);
			/*/
			//修改环信密码
			require_once(FRAMEWORK_PATH . "/class/emchat/Easemob.class.php");
			$options = array(
				"client_id" => $this->easemob_client_id,
				"client_secret" => $this->easemob_client_secret,
				"org_name" => $this->easemob_org_name,
				"app_name" => $this->easemob_app_name,
			);
			$easmob = new Easemob($options);
			$options = array(
				"username"=>$member->id,
				"newpassword"=>$new_password
			);
			$easmob->editPassword($options);
			//*/
			$this->_reload_session_info();
		}
		success('ok');
	}

	//我的订单列表
	//0：未支付，1：已支付，2：已完成，-1：取消
	public function order() {
		$keyword = isset($_GET['keyword']) ? trim($_GET['keyword']) : '';
		//PC我的订单包括全部状态
		if (isMobile()){
            $status = isset($_GET['status']) ? trim($_GET['status']) : 1;
        }else{
            $status = $this->request->get('status');
        }
		//积分商城订单
		$integral_order = (isset($_GET['integral_order']) && trim($_GET['integral_order'])) ? intval($_GET['integral_order']) : 0;
		$offset = (isset($_GET['offset']) && trim($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && trim($_GET['pagesize'])) ? intval($_GET['pagesize']) : 100;
		$where = " AND o.member_id='{$this->member_id}'";
		if (strlen($status)) {
			if ($status=='-2,-3') {
				$where .= " AND (o.status IN ({$status}) OR o.ask_refund_time>0)";
			} else {
				$where .= " AND o.status IN ({$status})";
			}
		}
		if ($keyword) {
			$where .= " AND (o.order_sn LIKE '%{$keyword}%' OR o.name LIKE '%{$keyword}%' OR o.mobile LIKE '%{$keyword}%')";
		}
		$where .= " AND o.integral_order='{$integral_order}' AND o.show=1";


        if (isMobile()){
            $sql = "SELECT o.*, '' as months, '' as shop_name FROM {$this->tbp}order o
			WHERE 1 {$where} ORDER BY o.id DESC LIMIT {$offset},{$pagesize}";
            //echo $sql;
            $orders = $this->db->get_results($sql);
        }else{
            $orders = SQL::share('order o')->isezr()->where($where)->limit(0,2)->order('o.id DESC')
                ->find("o.*, ''as months, '' as shop_name ");
            $nav = '';
            if ($orders){
                $nav = $this->ezr->get_navigation();
            }
        }


		if ($orders) {
			foreach ($orders as $k=>$o) {
				$months = explode(',', $o->month);
				foreach ($months as $key=>$month) {
					$months[$key] = str_replace('-','年',$month).'月';
				}
				$orders[$k]->months = $months;
				$orders[$k]->add_time = date('Y-m-d H:i:s', $o->add_time);
                $orders[$k]->city_name = SQL::share('city')->where("city_id='{$o->city}'")->val('name');
                //取得第一个和最后一个月份
                if (count($o->months)>1){
                    $orders[$k]->first_months = $o->months[0];
                    $orders[$k]->end_months = end($o->months);
                }
                $orders[$k]->count_months = count($o->months);
			}
		}

        //增加PC需要的内容
        if (!isMobile()){
            //消息
            $sql = "SELECT count(*) FROM {$this->tbp}message WHERE member_id='{$this->member_id}' AND readed=0";
            $notify = intval($this->db->get_var($sql));
            //优惠券总数
            $sql = "SELECT count(*) FROM {$this->tbp}coupon_sn WHERE member_id='{$this->member_id}' AND status=1";
            $coupon = intval($this->db->get_var($sql));
            //邀请人数
            $sql = "SELECT count(*) FROM {$this->tbp}member_invitation WHERE member_id='{$this->member_id}'";
            $invitation = intval($this->db->get_var($sql));
            //头像
            $sql = "SELECT avatar FROM {$this->tbp}member WHERE id='{$this->member_id}'";
            $avatar = $this->db->get_row($sql);
            //名称
            $sql = "SELECT nick_name FROM {$this->tbp}member WHERE id='{$this->member_id}'";
            $nick_name = $this->db->get_row($sql);

            //用来获取PC端now样式
            if ($status == '1,-1,-2'){
                $status = 5;
            }elseif ($status == '-1,-2'){
                $status = -1;
            }

            $count_order =  count(SQL::share('order')->where("member_id='{$this->member_id}' AND status=1")->find());
            success(array('orders'=>$orders, 'notify'=>$notify, 'coupon'=>$coupon, 'invitation'=>$invitation, 'avatar'=>$avatar , 'nick_name'=>$nick_name,
                'page'=>$nav, 'status'=>$status, 'count'=>$count_order));

        }else{
            success($orders);
        }


	}

	//订单详情
	public function order_detail($is_shop=false, $is_show=true) {
		$for_pay = (isset($_GET['for_pay']) && intval($_GET['for_pay'])) ? intval($_GET['for_pay']) : 0;
		if ($is_show && $for_pay>0) {
			$this->_order_detail_for_pay();
		}

		$order_sn = (isset($_GET['order_sn'])) ? $_GET['order_sn'] : '';
		$order_id = (isset($_GET['id']) && intval($_GET['id'])) ? intval($_GET['id']) : 0;
		$where = " (o.order_sn='{$order_sn}' OR o.parent_order_sn='{$order_sn}')";
		if ($order_id>0) $where = " o.id='{$order_id}'";
		$sql = "SELECT o.*, '' as months, p.name as province_name, c.name as city_name
			FROM {$this->tbp}order o
			LEFT JOIN {$this->tbp}province p ON p.province_id=o.province
			LEFT JOIN {$this->tbp}city c ON c.city_id=o.city
			WHERE {$where} AND o.member_id='{$this->member_id}'";
		//exit($sql);
		$order = $this->db->get_row($sql);
		if ($order) {
			//更新订单已阅读
			$sql = "UPDATE {$this->tbp}order o SET readed=1 WHERE {$where} AND o.member_id='{$this->member_id}'";
			$this->db->query($sql);
			
			$months = explode(',', $order->month);
			foreach ($months as $key=>$month) {
				$months[$key] = str_replace('-','年',$month).'月';
			}
			$order->months = $months;
			$order->add_time = date('Y-m-d H:i:s', $order->add_time);
			
			//退货退款申请
			$sql = "SELECT * FROM {$this->tbp}order_refund WHERE order_id='{$order->id}' ORDER BY id DESC";
			$g = $this->db->get_row($sql);
			if ($g) {
				$g->add_time = date('Y-m-d H:i:s', $g->add_time);
				$g->audit_time = date('Y-m-d H:i:s', $g->audit_time);
			}
			$order->refund = $g;
			//$order->add_time_word = date('Y-m-d H:i:s', $order->add_time);
			$order->pay_time_word = date('Y-m-d H:i:s', $order->pay_time);
			$order->shipping_time_word = date('Y-m-d H:i:s', $order->shipping_time);
			$order->shouhuo_time_word = date('Y-m-d H:i:s', $order->shouhuo_time);
			$order->delay_shouhuo_days = isset($this->configs['delay_shouhuo_days']) ? intval($this->configs['delay_shouhuo_days']) : 0;

            //查看用户有没有绑定手机号码(续费)
            $member= SQL::share('member')->where("id='{$this->member_id}'")->row();
            if ($member->mobile){
                $order->member_mobile = 1;
            }else{
                $order->member_mobile = 0;
            }

		}

		if ($is_show) {
			success($order, '成功', 0, array('jsApiParameters'=>NULL));
		} else {
			return $order;
		}
	}
	
	//直接可支付的order_detail
	private function _order_detail_for_pay() {
		$order_id = (isset($_GET['id']) && intval($_GET['id'])) ? intval($_GET['id']) : 0;
		$sql = "SELECT count(*) FROM {$this->tbp}order WHERE member_id='{$this->member_id}' AND id='{$order_id}'";
		if (intval($this->db->get_var($sql))<=0) error('您无此订单权限',-88);
		$program_order = (isset($_SESSION['program_order']) && trim($_SESSION['program_order'])) ? intval($_SESSION['program_order']) : 0;
		$order_sn = '';
		$total_price = 0;
		$order_body = '';
		$order = NULL;
		if ($order_id>0) {
			$order = $this->order_detail(false, false);
			if (!(intval($order->status)==0 || floatval($order->differ_money)>0)) {
				success($order, '成功', 0, array('jsApiParameters'=>NULL));
			}
			$_SESSION['origin_order_sn'] = '';
			$_SESSION['order_sn'] = '';
			$_SESSION['total_price'] = '';
			$_SESSION['order_body'] = '';
			$_SESSION['order_id'] = $order_id;
			$program_order = $this->is_mini;
			$_SESSION['program_order'] = $program_order;
			/*
			//确保库存足够
			$sql = "SELECT g.* FROM {$this->tbp}order_goods g LEFT JOIN {$this->tbp}order o ON o.id=g.order_id WHERE o.id='{$order_id}'";
			$goods = $this->db->get_results($sql);
			foreach ($goods as $k => $g) {
				$sql = "SELECT g.*, '' as spec, 0 as quantity
					FROM {$this->tbp}goods g INNER JOIN {$this->tbp}goods_spec gs ON g.id=gs.goods_id
					WHERE g.id='{$g->goods_id}' AND gs.spec='{$g->spec}'";
				//echo $sql;
				$row = $this->db->get_row($sql);
				if ($row) {
					$name = mb_substr($row->name, 0, 6);
					if ($g->quantity > $row->stocks) {
						error("商品（{$name}）库存不足");
					}
				}
			}
			*/
			//重新付款需要重写订单号,微信必须这么做
			if (intval($order->status)==0) {
				$pay_order_sn = generate_order_sn();
				$order->pay_order_sn = $pay_order_sn;
				$total_price = $order->total_price;
				$sql = "UPDATE {$this->tbp}order SET pay_order_sn='{$pay_order_sn}' WHERE id='{$order_id}'";
				$this->db->query($sql);
			} else {
				$pay_order_sn = 'CJ'.generate_order_sn();
				$order->pay_order_sn = $pay_order_sn;
				$total_price = $order->differ_money;
				$sql = "UPDATE {$this->tbp}order SET differ_order_sn='{$pay_order_sn}' WHERE id='{$order_id}'";
				$this->db->query($sql);
			}
		} else {
			$order_id = (isset($_SESSION['order_id']) && intval($_SESSION['order_id'])) ? intval($_SESSION['order_id']) : 0;
			if ($order_id<=0) error('订单信息错误！');
			$_GET = array('id'=>$order_id);
			$order = $this->order_detail(false, false);
			$total_price = $order->total_price;
		}

		$order_sn = $order->pay_order_sn;
		$order_body = intval($order->status)==0 ? '订单支付' : '订单差价支付';

		/**
		 * JS_API支付demo
		 * ====================================================
		 * 在微信浏览器里面打开H5网页中执行JS调起支付。接口输入输出数据格式为JSON。
		 * 成功调起支付需要三个步骤：
		 * 步骤1：网页授权获取用户openid
		 * 步骤2：使用统一支付接口，获取prepay_id
		 * 步骤3：使用jsapi调起支付
		*/
		include_once(FRAMEWORK_PATH . "/class/wxapi/WxPayPubHelper/WxPayPubHelper.php");

		//使用jsapi接口
		$jsApi = new JsApi_pub();
		$openid = '';

		if ($program_order==0) {
			//=========步骤1：网页授权获取用户openid============
			//通过code获得openid
			$code = (isset($_GET['code']) && trim($_GET['code'])) ? trim($_GET['code']) : '';
			if (!$code){
				//触发微信返回code码
				$url = $jsApi->createOauthUrlForCode(urlencode(https().$_SERVER['SERVER_NAME']."/wap.php?app=member&act=order_detail&for_pay=1&id={$order_id}"));
				// echo $url;exit;
				header("location: $url");
			}else{
				//获取code码，以获取openid
				$jsApi->setCode($code);
				$openid = $jsApi->getOpenid();
			}
		} else {
			$sql = "SELECT mini_openid FROM {$this->tbp}member WHERE id='{$this->member_id}'";
			$openid = $this->db->get_var($sql);
		}

		//=========步骤2：使用统一支付接口，获取prepay_id============
		//使用统一支付接口
		$unifiedOrder = new UnifiedOrder_pub();

		//设置统一支付接口参数
		//设置必填参数
		//appid已填,商户无需重复填写
		//mch_id已填,商户无需重复填写
		//noncestr已填,商户无需重复填写
		//spbill_create_ip已填,商户无需重复填写
		//sign已填,商户无需重复填写
		$unifiedOrder->setParameter("openid", "$openid");
		$unifiedOrder->setParameter("body", "$order_body");//商品描述
		if($order_sn==''){
			//自定义订单号，此处仅作举例
			$timeStamp = time();
			$order_sn = WxPayConf_pub::APPID."$timeStamp";
		}
		$unifiedOrder->setParameter("out_trade_no", "$order_sn");//商户订单号
		$unifiedOrder->setParameter("total_fee", $total_price*100);//总金额,单位:分
		$unifiedOrder->setParameter("notify_url", "http://".$_SERVER['SERVER_NAME']."/wx_notify_url.php");//通知地址
		$unifiedOrder->setParameter("trade_type", "JSAPI");//交易类型
		//非必填参数，商户可根据实际情况选填
		//$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号
		//$unifiedOrder->setParameter("device_info","XXXX");//设备号
		//$unifiedOrder->setParameter("attach","XXXX");//附加数据
		//$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
		//$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间
		//$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记
		//$unifiedOrder->setParameter("openid","XXXX");//用户标识
		//$unifiedOrder->setParameter("product_id","XXXX");//商品ID
		if ($program_order!=0) {
			$unifiedOrder->setMiniProgram(true);
			$jsApi->setMiniProgram(true);
		}

		$prepay_id = $unifiedOrder->getPrepayId();
		//=========步骤3：使用jsapi调起支付============
		$jsApi->setPrepayId($prepay_id);

		$jsApiParameters = $jsApi->getParameters();
		//exit($jsApiParameters);

		success( $order, '成功', 0, array('jsApiParameters'=>$jsApiParameters) );
		exit;
	}

	//删除订单
	public function order_delete() {
		$order_id = (isset($_GET['id']) && intval($_GET['id'])) ? intval($_GET['id']) : 0;
		SQL::share('order')->where($order_id)->update('`show`=0');
		success('ok');
	}

	//物流情况
	public function order_express() {
		$order_id = (isset($_GET['id']) && intval($_GET['id'])) ? intval($_GET['id']) : 0;
		if ($order_id<=0) error('数据错误');
		$sql = "SELECT *, '' as express FROM {$this->tbp}order WHERE id='{$order_id}' AND member_id='{$this->member_id}'";
		$order = $this->db->get_row($sql);
		if ($order) {
			$sql = "SELECT og.*, g.stocks, g.price as goods_price
				FROM {$this->tbp}order_goods og LEFT JOIN {$this->tbp}goods g ON og.goods_id=g.id WHERE order_id='{$order->id}'";
			$goods = $this->db->get_results($sql);
			$goods = add_domain_deep($goods, array("goods_pic"));
			$order->goods = $goods;
			$express = getkdniao($order->shipping_company, $order->shipping_number);
			if (is_array($express)) $express = array_reverse($express);
			$order->express = $express;
		}
		success($order);
	}

	//订单退款
	public function order_refund() {
		$id = $this->request->post('id', 0);
		if ($id<=0) error('缺少参数');
		$order = SQL::share('order')->where($id)->find();
		SQL::share('order')->where($id)->update("ask_refund_time='".time()."'");
		$out_refund_no = generate_order_sn();
		$sql = "INSERT INTO {$this->tbp}order_refund(order_id, member_id, pay_method, out_refund_no, type, price,
			reason, memo, pic1, pic2, pic3, status, add_time)
			VALUES ('{$id}', '{$order->member_id}', '{$order->pay_method}', '{$out_refund_no}', '1', '{$order->total_price}',
			'', '', '', '', '', '0', '".time()."')";
		$this->db->query($sql);
		success('ok');
	}

	//订单退款
	public function order_refund2() {
		$order_sn = (isset($_GET['order_sn'])) ? $_GET['order_sn'] : '';
		if (!$order_sn) exit;

		$sql = "SELECT * FROM {$this->tbp}order WHERE order_sn='{$order_sn}'";
		$order = $this->db->get_row($sql);
		if (!$order) exit;

		$out_refund_no = generate_order_sn();
		include_once(FRAMEWORK_PATH . "/class/wxapi/WxPayPubHelper/WxPayPubHelper.php");
		$refundApi = new Refund_pub();
		$refundApi->setParameter("out_trade_no", $order->order_sn); //原订单号
		$refundApi->setParameter("total_fee", $order->total_price*100); //订单金额
		$refundApi->setParameter("refund_fee", $order->total_price*100); //退款金额
		$refundApi->setParameter("op_user_id", WxPayConf_pub::MCHID); //操作员账号，一般为商户号
		$refundApi->setParameter("out_refund_no", $out_refund_no); //退款订单号
		print_r($refundApi->getResult());
		exit;
		//$sql = "INSERT INTO {$this->tbp}order_refund (order_id, out_refund_no, refund_fee, status, add_time)
		//		VALUES ('{$order->id}', '{$out_refund_no}', '{$order->total_price}', '0', '".time()."')";
		//$this->db->query($sql);
	}

	//我的订单的支付,微信端用
	public function order_pay() {
		if (IS_POST) {
			$_SESSION['origin_order_sn'] = '';
			$_SESSION['order_sn'] = '';
			$_SESSION['total_price'] = '';
			$_SESSION['order_body'] = '';
		}
		$order_sn = (isset($_POST['order_sn']) && trim($_POST['order_sn'])) ? trim($_POST['order_sn']) : '';
		$total_price = (isset($_POST['price']) && trim($_POST['price'])) ? floatval($_POST['price']) : 0;
		$order_body = (isset($_POST['body']) && trim($_POST['body'])) ? trim($_POST['body']) : '';
		//重新付款需要重写订单号,微信必须这么做
		if ($order_sn!='') {
			$_SESSION['origin_order_sn'] = $order_sn;
			$pay_order_sn = generate_order_sn();
			$sql = "UPDATE {$this->tbp}order SET pay_order_sn='{$pay_order_sn}' WHERE order_sn='{$order_sn}'";
			$this->db->query($sql);
			$order_sn = $pay_order_sn;
		}
		if ($order_sn=='' || $total_price<=0) {
			$order_sn = (isset($_SESSION['order_sn']) && trim($_SESSION['order_sn'])) ? trim($_SESSION['order_sn']) : '';
			$total_price = (isset($_SESSION['total_price']) && trim($_SESSION['total_price'])) ? floatval($_SESSION['total_price']) : 0;
			$order_body = (isset($_SESSION['order_body']) && trim($_SESSION['order_body'])) ? trim($_SESSION['order_body']) : '';
		}
		if ($order_sn=='' || $total_price<=0) {
			error('订单信息错误！');
		}
		$_SESSION['order_sn'] = $order_sn;
		$_SESSION['total_price'] = $total_price;
		$_SESSION['order_body'] = $order_body;

		//确保库存足够
		$sql = "SELECT g.* FROM {$this->tbp}order_goods g LEFT JOIN {$this->tbp}order o ON o.id=g.order_id WHERE o.order_sn='{$order_sn}'";
		$goods = $this->db->get_results($sql);
		foreach ($goods as $k => $g) {
			$sql = "SELECT g.*, '' as spec, 0 as quantity
				FROM {$this->tbp}goods g INNER JOIN {$this->tbp}goods_spec gs ON g.id=gs.goods_id
				WHERE g.id='{$g->goods_id}' AND gs.spec='{$g->spec}'";
			//echo $sql;
			$row = $this->db->get_row($sql);
			if ($row) {
				$name = mb_substr($row->name, 0, 6);
				if ($g->quantity > $row->stocks) {
					error("商品（{$name}）库存不足");
				}
			}
		}

		/**
		 * JS_API支付demo
		 * ====================================================
		 * 在微信浏览器里面打开H5网页中执行JS调起支付。接口输入输出数据格式为JSON。
		 * 成功调起支付需要三个步骤：
		 * 步骤1：网页授权获取用户openid
		 * 步骤2：使用统一支付接口，获取prepay_id
		 * 步骤3：使用jsapi调起支付
		*/
		include_once(FRAMEWORK_PATH . "/class/wxapi/WxPayPubHelper/WxPayPubHelper.php");

		//使用jsapi接口
		$jsApi = new JsApi_pub();

		//=========步骤1：网页授权获取用户openid============
		//通过code获得openid
		$openid = '';
		$code = (isset($_GET['code']) && trim($_GET['code'])) ? trim($_GET['code']) : '';
		if (!$code){
			//触发微信返回code码
			$url = $jsApi->createOauthUrlForCode(urlencode(https().$_SERVER['SERVER_NAME']."/wap.php?app=member&act=order_pay"));
			header("location: $url");
		}else{
			//获取code码，以获取openid
			$jsApi->setCode($code);
			$openid = $jsApi->getOpenid();
		}

		//=========步骤2：使用统一支付接口，获取prepay_id============
		//使用统一支付接口
		$unifiedOrder = new UnifiedOrder_pub();

		//设置统一支付接口参数
		//设置必填参数
		//appid已填,商户无需重复填写
		//mch_id已填,商户无需重复填写
		//noncestr已填,商户无需重复填写
		//spbill_create_ip已填,商户无需重复填写
		//sign已填,商户无需重复填写
		$unifiedOrder->setParameter("openid", "$openid");
		$unifiedOrder->setParameter("body", "$order_body");//商品描述
		if($order_sn==''){
			//自定义订单号，此处仅作举例
			$timeStamp = time();
			$order_sn = WxPayConf_pub::APPID."$timeStamp";
		}
		$unifiedOrder->setParameter("out_trade_no", "$order_sn");//商户订单号
		$unifiedOrder->setParameter("total_fee", $total_price*100);//总金额,单位:分
		$unifiedOrder->setParameter("notify_url", "http://".$_SERVER['SERVER_NAME']."/wx_notify_url.php");//通知地址
		$unifiedOrder->setParameter("trade_type", "JSAPI");//交易类型
		//非必填参数，商户可根据实际情况选填
		//$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号
		//$unifiedOrder->setParameter("device_info","XXXX");//设备号
		//$unifiedOrder->setParameter("attach","XXXX");//附加数据
		//$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
		//$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间
		//$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记
		//$unifiedOrder->setParameter("openid","XXXX");//用户标识
		//$unifiedOrder->setParameter("product_id","XXXX");//商品ID

		$prepay_id = $unifiedOrder->getPrepayId();
		//=========步骤3：使用jsapi调起支付============
		$jsApi->setPrepayId($prepay_id);

		$jsApiParameters = $jsApi->getParameters();
		//exit($jsApiParameters);

		$order_sn = $_SESSION['origin_order_sn'];
		success( $jsApiParameters, '成功', 0, array('order_sn'=>$order_sn) );
	}

	//修改订单价格
	public function order_change_price() {
		$order_id = (isset($_POST['id']) && intval($_POST['id'])) ? intval($_POST['id']) : 0;
		$price = (isset($_POST['price']) && floatval($_POST['price'])) ? floatval($_POST['price']) : 0;
		if ($order_id) {
			$sql = "SELECT status FROM {$this->tbp}order WHERE id='{$order_id}' AND shop_id='{$this->shop_id}'";
			$status = intval($this->db->get_var($sql));
			if ($status!=0) error('只有未支付的订单才能修改价格');
			$sql = "UPDATE {$this->tbp}order SET total_price='{$price}' WHERE id='{$order_id}' AND shop_id='{$this->shop_id}'";
			$this->db->get_row($sql);
		}
		success("ok");
	}

	//取消订单
	public function order_cancel() {
		$order_id = (isset($_POST['id']) && trim($_POST['id'])) ? intval($_POST['id']) : 0;
		$sql = "SELECT shop_id, total_price, status FROM {$this->tbp}order WHERE id='{$order_id}' AND member_id='{$this->member_id}'";
		$order = $this->db->get_row($sql);
		if (!$order) error('数据错误');
		//设置状态
		$sql = "UPDATE {$this->tbp}order SET status='-1', cancel_time='".time()."' WHERE id='{$order_id}' AND member_id='{$this->member_id}'";
		$this->db->query($sql);
		if ($order->status>0) {
			/*
			//减少收入
			$total_price = floatval($order->total_price);
			if ($total_price) {
				$sql = "SELECT member_id FROM {$this->tbp}shop WHERE id='{$order->shop_id}'";
				$member_id = intval($this->db->get_var($sql));
				$sql = "SELECT total_income FROM {$this->tbp}shop WHERE id='{$member_id}'";
				$total_income = floatval($this->db->get_var($sql));
				if ($total_price >= $total_income) {
					$income = 0;
				} else {
					$income = $total_income - $total_price;
				}
				$sql = "UPDATE {$this->tbp}shop SET total_income={$income} WHERE id='{$order->shop_id}'";
				$this->db->query($sql);
				//echo $income;
				//$_SESSION['member']->total_income = $income;
			}
			*/
		}
		success('ok');
	}

	//20171213 by @jsong 自动收货、自动退款已交由 cron 统一处理

	//确认收货
	public function order_shouhuo() {
		$order_id = (isset($_POST['id']) && trim($_POST['id'])) ? intval($_POST['id']) : 0;
		$this->order_mod->shouhuo($order_id);
		success('ok');
	}

	//获取快递公司列表与订单的相关商品
	public function get_shipping_company_and_goods() {
		$order_id = (isset($_GET['order_id']) && trim($_GET['order_id'])) ? intval($_GET['order_id']) : 0;
		$shippings = $this->shipping_company(false);
		$sql = "SELECT goods_id as id, goods_name, goods_pic, qrcode, spec, quantity FROM {$this->tbp}order_goods
			WHERE shop_id='{$this->shop_id}' AND order_id='{$order_id}'";
		$goods = $this->db->get_results($sql);
		$goods = add_domain_deep($goods, array("goods_pic"));
		success(array("shipping_company"=>$shippings, "goods"=>$goods));
	}

	//我的发现
	public function article() {
		$offset = (isset($_GET['offset']) && trim($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && trim($_GET['pagesize'])) ? intval($_GET['pagesize']) : 8;
		if ($this->member_id<=0) error('请登录', -100);
		$sql = "SELECT * FROM {$this->tbp}article WHERE member_id='{$this->member_id}' ORDER BY sort ASC, id DESC LIMIT {$offset}, {$pagesize}";
		$articles = $this->db->get_results($sql);
		if ($articles) {
			foreach ($articles as $k=>$article) {
				$sql = "SELECT pic FROM {$this->tbp}article_pic WHERE article_id='{$article->id}' ORDER BY id ASC LIMIT 3";
				$pics = $this->db->get_results($sql);
				$articles[$k]->pics = $pics;
				$sql = "SELECT goods_id FROM {$this->tbp}article_goods WHERE article_id='{$article->id}' ORDER BY id ASC";
				$goods = $this->db->get_results($sql);
				$articles[$k]->goods = $goods;
				$articles[$k]->add_time = get_time_word($article->add_time);
			}
		}
		success($articles);
	}

	//删除我的发现
	public function article_delete() {
		$id = (isset($_POST['id']) && trim($_POST['id'])) ? intval($_POST['id']) : 0;
		$sql = "DELETE FROM {$this->tbp}article WHERE member_id='{$this->member_id}' AND id='{$id}'";
		$this->db->query($sql);
		success('ok');
	}

	//获取快递公司列表
	public function shipping_company($is_show=true) {
		$sql = "SELECT pinyin, name FROM {$this->tbp}shipping_company ORDER BY sort ASC, name ASC";
		$results = $this->db->get_results($sql);
		if ($is_show) {
			success($results);
		} else {
			return $results;
		}
	}

	//根据标签码获取商品ID
	public function get_goods_id_from_qrcode() {
		$code = (isset($_GET['code']) && trim($_GET['code'])) ? trim($_GET['code']) : '';
		$sql = "SELECT goods_id FROM {$this->tbp}factory_code WHERE code='{$code}' ORDER BY id DESC";
		$goods_id = $this->db->get_var($sql);
		if ($goods_id) {
			success($goods_id);
		} else {
			error('该标签没有绑定到商品');
		}
	}

	//退款退货申请
	public function refund() {
		$order_id = (isset($_POST['order_id']) && trim($_POST['order_id'])) ? intval($_POST['order_id']) : 0;
		$type = (isset($_POST['type']) && trim($_POST['type'])) ? intval($_POST['type']) : 0; //1:退款, 2:退货
		//$price = (isset($_POST['price']) && floatval($_POST['price'])) ? floatval($_POST['price']) : 0;
		$reason = (isset($_POST['reason']) && trim($_POST['reason'])) ? trim($_POST['reason']) : '';
		$memo = (isset($_POST['memo']) && trim($_POST['memo'])) ? trim($_POST['memo']) : '';
		$pic1 = (isset($_POST['pic1']) && trim($_POST['pic1'])) ? trim($_POST['pic1']) : '';
		$pic2 = (isset($_POST['pic2']) && trim($_POST['pic2'])) ? trim($_POST['pic2']) : '';
		$pic3 = (isset($_POST['pic3']) && trim($_POST['pic3'])) ? trim($_POST['pic3']) : '';
		if (!$order_id) error('无效的订单号');

		$sql = "SELECT order_sn FROM {$this->tbp}order WHERE id='{$order_id}' AND member_id='{$this->member_id}' AND status>0";
		$order = $this->db->get_row($sql);
		if (!$order) error('订单不存在!');

		//把parent_order_sn设置为order_sn
		//$sql = "UPDATE {$this->tbp}order SET parent_order_sn='{$order->order_sn}' WHERE id='{$order_id}'";
		//$this->db->query($sql);

		$sql = "SELECT member_id, mobile, total_price, pay_method, parent_order_sn, trade_no, status FROM {$this->tbp}order WHERE id='{$order_id}'";
		//exit($sql);
		$order = $this->db->get_row($sql);
		$out_refund_no = generate_order_sn();

		$pic1 = upload_one_file('uploadfiles/refund', 'pic1');
		$pic2 = upload_one_file('uploadfiles/refund', 'pic2');
		$pic3 = upload_one_file('uploadfiles/refund', 'pic3');

		$sql = "INSERT INTO {$this->tbp}order_refund(order_id, member_id, pay_method, out_refund_no, type, price,
			reason, memo, pic1, pic2, pic3, status, add_time)
			VALUES ('{$order_id}', '{$order->member_id}', '{$order->pay_method}', '{$out_refund_no}', '{$type}', '{$order->total_price}',
			'{$reason}', '{$memo}', '{$pic1}', '{$pic2}', '{$pic3}', '0', '".time()."')";
		$this->db->query($sql);

		//20160428 by @jsong 要求任何状态都需要厂家审核
		//$r = "原因：{$reason}";
		//if ($memo) $r .= chr(13).chr(10)."说明：{$memo}";
		$this->order_return_goods();
		//success('您的申请已提交，请耐心等待商家处理');
	}

	//第三方退款
	public function _refund($order_id, $order_sn, $trade_no, $total_price, $pay_method, $out_refund_no, $refund_id=0, $member_id=0, $is_show=true) {
		if ($pay_method=='wxpay' || $pay_method=='wxpay_h5') {
			if ($pay_method=='wxpay') {
				include_once(FRAMEWORK_PATH . "/class/wxapi/RefundAppHelper/WxPay.Api.php");
			} else {
				include_once(FRAMEWORK_PATH . "/class/wxapi/RefundWxHelper/WxPay.Api.php");
			}
			$input = new WxPayRefund();
			if ($trade_no!='') {
				$input->SetTransaction_id($trade_no); //微信订单号
			} else {
				$input->SetOut_trade_no($order_sn); //原订单号
			}
			$input->SetTotal_fee($total_price*100); //订单金额，单位分
			$input->SetRefund_fee($total_price*100); //退款金额
			$input->SetOp_user_id(WxPayConfig::MCHID); //操作员账号，一般为商户号
			$input->SetOut_refund_no($out_refund_no); //退款订单号
			//$input->SetRefund_account('REFUND_SOURCE_RECHARGE_FUNDS'); //退款资金来源
			$data = WxPayApi::refund($input);
			//foreach ($data as $k=>$v) echo "<font color='#f00;'>$k</font> : $v<br/>";exit;
			if ($data["return_code"]=='SUCCESS') {
				if ($data["result_code"]=='SUCCESS') {
					$sql = "UPDATE {$this->tbp}order_refund SET status='1' WHERE id='{$refund_id}'";
					$this->db->query($sql);
					$sql = "UPDATE {$this->tbp}order SET status='-2' WHERE id='{$order_id}'";
					$this->db->query($sql);
				} else {
					if ($is_show) error($data["err_code_des"]);
				}
			} else {
				if ($is_show) error($data["return_msg"]);
			}
		} else if ($pay_method=='alipay') {
			require_once(FRAMEWORK_PATH . "/class/alipay/alipay.config.php");
			require_once(FRAMEWORK_PATH . "/class/alipay/lib/alipay_refund_nopwd_service.php");
			$seller_email = $alipay_config['seller_email']; //卖家支付宝帐户
			$refund_date = date('Y-m-d H:i:s'); //退款当天日期
			$batch_no = date('YmdHis'); //批次号, 格式：当天日期[8位]+序列号[3至24位]，如：201008010000001
			$batch_num = 1; //退款笔数
			//必填，参数detail_data的值中，“#”字符出现的数量加1，最大支持1000笔（即“#”字符出现的数量999个）
			$detail_data = "{$trade_no}^{$total_price}^买家主动退款"; //退款详细数据
			//必填，具体格式请参见接口技术文档，单笔退款数据集格式：原付款支付宝交易号^退款总金额^退款理由
			$notify_url = "http://".$_SERVER['SERVER_NAME']."/notify_url_refund.php"; //异步通知页面
			//构造要请求的参数数组，无需改动
			$parameter = array(
				//接口名称，不需要修改
				"service"			=> "refund_fastpay_by_platform_nopwd",
				//获取配置文件(alipay_config.php)中的值
				"partner"			=> trim($alipay_config['partner']),
				"notify_url"		=> $notify_url,
				"_input_charset"	=> trim(strtolower($alipay_config['input_charset'])),
				//必填参数
				"refund_date"		=> $refund_date,
				"batch_no"			=> $batch_no,
				"batch_num"			=> $batch_num,
				"detail_data"		=> $detail_data
			);
			//构造请求函数, 配置环境须支持SSL
			$alipay = new alipay_refund_nopwd_service($parameter, $alipay_config['key'], $alipay_config['sign_type_refund']);
			$url = $alipay->create_url();
			$data = file_get_contents($url);
			$nodeIs_success = '';
			$nodeError_code = '';
			$obj = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
			$obj = (array)$obj;
			//writeLog(json_encode($obj));
			if (isset($obj['is_success'])) $nodeIs_success = $obj['is_success']; //获取成功标识is_success
			if (isset($obj['error'])) $nodeError_code = $obj['error']; //获取错误代码 error
			if ($nodeIs_success=="T") {
				$sql = "UPDATE {$this->tbp}order_refund SET status='1' WHERE id='{$refund_id}'";
				$this->db->query($sql);
				$sql = "UPDATE {$this->tbp}order SET status='-2' WHERE id='{$order_id}'";
				$this->db->query($sql);
			} else {
				if ($is_show) error($nodeError_code);
			}
		} else if ($pay_method=='yue') {
			$sql = "UPDATE {$this->tbp}member SET money=money+{$total_price} WHERE id='{$member_id}'";
			$this->db->query($sql);
			$sql = "UPDATE {$this->tbp}order_refund SET status='1' WHERE id='{$refund_id}'";
			$this->db->query($sql);
			$sql = "UPDATE {$this->tbp}order SET status='-2' WHERE id='{$order_id}'";
			$this->db->query($sql);
		}
	}

	//退货退款申请，1:退款, 2:退货
	public function order_return_goods($reason='') {
		$order_id = (isset($_POST['order_id']) && trim($_POST['order_id'])) ? intval($_POST['order_id']) : 0;
		$type = (isset($_POST['type']) && trim($_POST['type'])) ? intval($_POST['type']) : 0; //1:退款, 2:退货
		if (!$reason) $reason = (isset($_POST['reason']) && trim($_POST['reason'])) ? trim($_POST['reason']) : '';
		if (!$order_id) error('数据错误');
		/*
		//remark by ajsong 2016-7-13 yidian的数据库操作
		$sql = "SELECT factory_shop_id, s.member_id as shop_member_id, m.name as member_name FROM {$this->tbp}order o
			LEFT JOIN {$this->tbp}member m ON o.member_id=m.id
			LEFT JOIN {$this->tbp}shop s ON o.factory_shop_id=s.id
			WHERE o.id='{$order_id}'";
		$order = $this->db->get_row($sql);
		$sql = "INSERT INTO {$this->tbp}order_refund (order_id, shop_id, member_id, type, reason, status, add_time)
			VALUES ('{$order_id}', '{$order->factory_shop_id}', '{$this->member_id}', '{$type}', '{$reason}', '0', '".time()."')";
		$this->db->query($sql);
		*/
		$sql = "SELECT m.name as member_name FROM {$this->tbp}order o LEFT JOIN {$this->tbp}member m ON o.member_id=m.id WHERE o.id='{$order_id}'";
		$order = $this->db->get_row($sql);

		$sql = "UPDATE {$this->tbp}order SET ask_refund_time='".time()."' WHERE id='{$order_id}'";
		$this->db->query($sql);

		$str = '退款';
		if ($type==2) $str = '退货';
		success("ok", "{$str}申请已提交，请耐心等待商家处理");
	}

	//退货退款审核，1:退款, 2:退货
	public function order_check_return_goods($order_id=0, $reason='', $status=1, $is_show=true) {
		if ($order_id<=0) {
			$order_id = (isset($_POST['order_id']) && trim($_POST['order_id'])) ? intval($_POST['order_id']) : 0;
			$reason = (isset($_POST['reason']) && trim($_POST['reason'])) ? trim($_POST['reason']) : '';
			$status = (isset($_POST['status']) && trim($_POST['status'])) ? intval($_POST['status']) : 0;
		}
		if ($order_id) {
			//判断是退款还是退货
			$sql = "SELECT type FROM {$this->tbp}order_refund WHERE order_id='{$order_id}' ORDER BY id DESC";
			$type = $this->db->get_var($sql);

			$sql = "SELECT o.*, s.member_id as shop_member_id FROM {$this->tbp}order o
				LEFT JOIN {$this->tbp}shop s ON factory_shop_id=s.id
				WHERE o.id='{$order_id}'";
			$order = $this->db->get_row($sql);

			if ($status==1) {
				$sql = "SELECT id, out_refund_no FROM {$this->tbp}order_refund WHERE order_id='{$order_id}' ORDER BY id DESC";
				$refund = $this->db->get_row($sql);
				$this->_refund($order_id, $order->parent_order_sn, $order->trade_no, $order->total_price, $order->pay_method, $refund->out_refund_no, $refund->id, $order->member_id, $is_show);
				if ($type==1) {
					$reason = "已退款";
				} else {
					$sql = "UPDATE {$this->tbp}order SET status='-3' WHERE id='{$order_id}'";
					$this->db->query($sql);
					$sql = "SELECT factory_shop_id FROM {$this->tbp}order WHERE id='{$order_id}'";
					$shop_id = $this->db->get_var($sql);
					$sql = "SELECT return_province, return_city, return_district, return_address, return_name, return_mobile
						FROM {$this->tbp}shop WHERE id='{$shop_id}'";
					$row = $this->db->get_row($sql);
					$reason = "退货地址：{$row->return_province}{$row->return_city}{$row->return_district}{$row->return_address}，联系人：{$row->return_name}，电话：{$row->return_mobile}";
				}
				//扣减退货退款后店铺的佣金 by willson 2016/5/4
				$this->_reduce_order_commission($order_id);
			}
			$sql = "UPDATE {$this->tbp}order_refund SET status='{$status}', audit_time='".time()."', audit_memo='{$reason}' WHERE order_id='{$order_id}'";
			$this->db->query($sql);

			//发送短信、推送
			$member_id = -1;
			$notify = '';
			$sms = array();
			$template_id = 0;
			if ($status==1) {
				if ($type==1) {
					$member_id = $order->member_id;
					$notify = "您的订单{$order->order_sn}退款成功，退款金额为{$order->total_price}元";
					$sms = array($order->order_sn, "{$order->total_price}元");
					$template_id = 221218;
				} else {
					$member_id = $order->member_id;
					$notify = "您的订单{$order->order_sn}退货成功";
					$sms = array($order->order_sn);
					$template_id = 221222;
				}
			} else {
				if ($type==1) {
					$member_id = $order->member_id;
					$notify = "您申请的退款请求失败，请联系卖家";
					$template_id = 221225;
				} else {
					$member_id = $order->member_id;
					$notify = "您申请的退货请求失败，请联系卖家";
					$template_id = 221226;
				}
			}
			$this->send_notify_sms($notify, $member_id, $sms, $template_id);

			if ($status==1 && $type==1) {
				switch ($order->pay_method) {
					case 'wxpay':
					case 'wxpay_h5':
					case 'alipay':
						if ($is_show) {
							success('订单已退款，请及时检查您的第三方支付平台的账户，若未收到款项请尽快联系我们');
						}
						break;
					case 'yue':
						if ($order->member_id == $this->member_id) {
							if ($is_show) {
								success('订单已退款，请在会员中心查看您的余额是否已到账');
							}
						}
						break;
				}
			}
		}
		if ($is_show) {
			success('ok');
		}
	}

	//退货退款成功后，扣减店铺的佣金
	public function _reduce_order_commission($order_id) {
		$sql = "SELECT * FROM {$this->tbp}member_commission WHERE parent_id='{$order_id}' AND type=1 AND status=1";
		$rs = $this->db->get_results($sql);
		if ($rs) {
			foreach ($rs as $k => $g) {
				$money = $g->commission;
				if ($money) {
					//处理店铺佣金
					$sql = "SELECT shop_id FROM {$this->tbp}order WHERE id='{$g->parent_id}'";
					$order = $this->db->get_row($sql);
					if ($order) {
						$sql = "SELECT total_income, can_withdraw_money, member_id FROM {$this->tbp}shop WHERE id='{$order->shop_id}'";
						$shop = $this->db->get_row($sql);
						if ($shop) {
							if ($shop->total_income>=$money) {
								$shop->total_income = $shop->total_income - $money;
							} else {
								$shop->total_income = 0;
							}
							if ($shop->can_withdraw_money>=$money) {
								$shop->can_withdraw_money = $shop->can_withdraw_money - $money;
							} else {
								$shop->can_withdraw_money = 0;
							}
							$sql = "UPDATE {$this->tbp}shop SET total_income='{$shop->total_income}',
								can_withdraw_money='{$shop->can_withdraw_money}' WHERE id='{$order->shop_id}'";
							$this->db->query($sql);
							//处理会员佣金
							$sql = "SELECT commission FROM {$this->tbp}member WHERE id='{$shop->member_id}'";
							$member = $this->db->get_row($sql);
							if ($member) {
								if ($member->commission>=$money) {
									$member->commission = $member->commission - $money;
								} else {
									$member->commission = 0;
								}
								$sql = "UPDATE {$this->tbp}member SET commission='{$member->commission}' WHERE id='{$shop->member_id}'";
								$this->db->query($sql);
							}
						}
					}
				}
			}
		}
		$sql = "UPDATE {$this->tbp}member_commission SET status='-1' WHERE parent_id='{$order_id}' AND type=1";
		$this->db->query($sql);
	}

	//通过会员id读取头像
	public function get_avatar() {
		$members = "";
		$avatar = '';
		$nick_name = '';
		$ids = '';
		$member_ids = (isset($_GET['member_id']) && trim($_GET['member_id'])) ? $_GET['member_id'] : '';
		if ($member_ids) {
			$arr = explode(',', $member_ids);
			foreach ($arr as $value) {
				if (is_numeric($value)) $ids .= ','.$value;
			}
			$ids = trim($ids, ',');
			$sql = "SELECT m.id, m.name, m.avatar, m.real_name, m.member_type, m.mobile as member_mobile, m.qq as member_qq, m.weixin as member_weixin,
				s.mobile as shop_mobile, s.qq as shop_qq, s.weixin as shop_weixin, s.name as shop_name, s.avatar as shop_avatar, s.status
				FROM {$this->tbp}member m LEFT JOIN {$this->tbp}shop s ON m.id=s.member_id
				WHERE m.id IN ({$ids})";
			$members = $this->db->get_results($sql);
			if ($members) {
				foreach ($members as $k=>$m) {
					$obj = new stdClass();
					$obj->id = $m->id;
					/*/
					$obj->name = $m->name;
					$obj->avatar = $m->avatar;
					$obj->mobile = $m->member_mobile;
					$obj->qq = $m->member_qq;
					$obj->weixin = $m->member_weixin;
					//*/
					if ($m->member_type==3) {
						$obj->name = $m->shop_name;
						$obj->avatar = $m->shop_avatar;
						$obj->mobile = $m->shop_mobile;
						$obj->qq = $m->shop_qq;
						$obj->weixin = $m->shop_weixin;
					} else {
						if ($m->real_name) {
							$obj->name = $m->real_name;
						} else {
							$obj->name = $m->name;
						}
						$obj->avatar = $m->avatar;
						$obj->mobile = $m->member_mobile;
						$obj->qq = $m->member_qq;
						$obj->weixin = $m->member_weixin;
					}
					//*/
					$members[$k] = $obj;
				}
				$members = add_domain_deep($members, array("avatar"));
			}
		}
		success($members);
	}

	//通过会员id获取会员的联系方式、微信、qq（非常不安全的做法）
	public function get_contact() {
		$mobile = $qq = $weixin = "";
		$member_id = (isset($_GET['member_id']) && trim($_GET['member_id'])) ? intval($_GET['member_id']) : 0;
		if ($member_id) {
			//先读取店铺
			$sql = "SELECT s.mobile, s.qq, s.weixin FROM {$this->tbp}shop s LEFT JOIN {$this->tbp}member m ON s.member_id=m.id
				WHERE m.id='{$member_id}'";
			$row = $this->db->get_row($sql);
			//店铺的不存在，读取会员的
			if (!$row) {
				$sql = "SELECT mobile, qq, weixin FROM {$this->tbp}member WHERE id='{$member_id}'";
				$row = $this->db->get_row($sql);
			}
			if ($row) {
				$mobile = $row->mobile;
				$qq = $row->qq;
				$weixin = $row->weixin;
			}
		}
		success(array("mobile"=>$mobile, "qq"=>$qq, "weixin"=>$weixin));
	}

	//重新加载会员的SESSION，一般在设置了大量的个人信息后
	private function _reload_session_info() {
		$sql = "SELECT * FROM {$this->tbp}member WHERE id='{$this->member_id}'";
		$member = $this->db->get_row($sql);
		if ($member) {
			//导致shop_id丢失
			$_SESSION['member'] = $member;
			return true;
		}  else {
			return false;
		}
	}

	//已邀请用户
	public function my_invite_user() {
		$members = null;
		$offset = (isset($_GET['offset']) && trim($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && trim($_GET['pagesize'])) ? intval($_GET['pagesize']) : 8;
		if ($this->member_id) {
			$sql = "SELECT m.id, m.name, m.avatar, m.reg_time, m.mobile
				FROM {$this->tbp}member m
				WHERE m.parent_id='{$this->member_id}' ORDER BY m.id DESC
				LIMIT {$offset}, {$pagesize}";
			$members = $this->db->get_results($sql);
			if ($members) {
				foreach ($members as $k => $member) {
					if (!$member->name) {
						$members[$k]->name = $member->mobile;
					}
					$members[$k]->reg_time = date("Y-m-d", $member->reg_time);
				}
				$members = add_domain_deep($members, array("avatar"));
			}
		}
		success($members);
	}

	//我的店员列表
	public function clerk() {
		$offset = (isset($_GET['offset']) && trim($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && trim($_GET['pagesize'])) ? intval($_GET['pagesize']) : 8;
		$clerks = null;
		if ($this->member_id && $_SESSION['member']->member_type==3) {
			//店员
			$sql = "SELECT * FROM {$this->tbp}member WHERE shopowner_id='{$this->member_id}' ORDER BY id DESC LIMIT {$offset}, {$pagesize}";
			$clerks = $this->db->get_results($sql);
			//店员所带来的订单总额
			if($clerks){
				foreach ($clerks as $key => $val) {
					$sql = "SELECT sum(total_price) FROM {$this->tbp}order WHERE member_id in (SELECT id
						FROM {$this->tbp}member WHERE parent_id = {$val->id} OR id = {$val->id})
						AND status > 0 ORDER BY total_price DESC";
					// $sql = "SELECT sum(total_price) FROM {$this->tbp}order WHERE member_id='{$val->id}'";
					$val->total_price = $this->db->get_var($sql);
					// print_r($sql);exit;
				}
			}
		}
		success($clerks);
	}

	//店员带来订单
	public function clerk_order() {
		$clerks = null;
		$where = '';
		$nav = '';
		$empt = '';
		// $offset = (isset($_GET['offset']) && trim($_GET['offset'])) ? intval($_GET['offset']) : 0;
		// $pagesize = (isset($_GET['pagesize']) && trim($_GET['pagesize'])) ? intval($_GET['pagesize']) : 8;
		$clerk_id = (isset($_GET['clerk_id']) && trim($_GET['clerk_id'])) ? intval($_GET['clerk_id']) : 0;
		$sign = (isset($_GET['sign']) && trim($_GET['sign'])) ? trim($_GET['sign']) : '';
		$starttime = (isset($_GET['starttime']) && trim($_GET['starttime'])) ? trim($_GET['starttime']) : 0;
		$endtime = (isset($_GET['endtime']) && trim($_GET['endtime'])) ? trim($_GET['endtime']) : 0;
		$starttime = strtotime($starttime);
		$endtime = strtotime($endtime);
		$clerk_order = null;
		//判断该店员是否属于该店张
		$sql = "SELECT * FROM {$this->tbp}member WHERE shopowner_id = {$this->member_id} AND id = {$clerk_id}";
		$sure = $this->db->get_var($sql);
		if ($this->member_id && $clerk_id && $sure) {
			if($starttime>0 && $endtime>0){
				$where .= " AND o.add_time>={$starttime} AND o.add_time<={$endtime}";
			}
			//分页
			// $this->ezr->num_results_per_page=5;
			$this->setpages(array('endtime'=>$endtime,'starttime'=>$starttime,'clerk_id'=>$clerk_id));
			//店员所带来的订单
			$sql = "SELECT id FROM {$this->tbp}member WHERE parent_id='{$clerk_id}'";
			$a = $this->db->get_results($sql);
			//店员带来的订单（包含自身订单）
			$where_a = "{$clerk_id} ,";
			if($a){
				foreach ($a as $key => $val) {
					$where_a .= "{$val->id} ,";
				}
			}
			$where_a =substr($where_a, 0 , -1);
			$sql = "SELECT o.order_sn ,o.add_time ,o.total_price FROM {$this->tbp}order o
					WHERE member_id in ({$where_a}) AND o.status > 0 {$where}
					ORDER BY o.add_time DESC";
			$clerk_order = $this->ezr->get_results($sql);
			$nav = $this->ezr->get_navigation();

			if ($clerk_order) {
				foreach ($clerk_order as $k => $row) {
					$clerk_order[$k]['add_time'] = date("m-d", $row['add_time']);
				}
			}
			if($starttime && $endtime){
				$starttime = date("Y-m-d", $starttime);
				$endtime = date("Y-m-d", $endtime);
			}
		}else{
			$empt = '请确认是否是所属店员！';
		}

		success(array("clerk_order"=>$clerk_order, "clerk_id"=>$clerk_id, "sign"=>$sign,
			"nav"=>$nav,"starttime"=>$starttime,"endtime"=>$endtime ,'empt'=>$empt));
	}

	//我的店员
	public function sells() {
		$offset = (isset($_GET['offset']) && trim($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && trim($_GET['pagesize'])) ? intval($_GET['pagesize']) : 8;
		$rs = null;
		if ($this->member_id && $_SESSION['member']->member_type==3) {
			$sql = "SELECT * FROM {$this->tbp}member WHERE shopowner_id='{$this->member_id}' ORDER BY id DESC LIMIT {$offset}, {$pagesize}";
			$rs = $this->db->get_results($sql);
		}
		success($rs);
	}

	//会员等级列表
	public function grade_list() {
		$price = (isset($_GET['price']) && intval($_GET['price'])) ? intval($_GET['price']) : 0;
		$orderby = (isset($_GET['orderby']) && trim($_GET['orderby'])) ? trim($_GET['orderby']) : 'ASC';
		$orderby = strtoupper($orderby);
		$where = '';
		if ($price>0) $where = " AND price>0";
		if ($orderby!='ASC' && $orderby!='DESC') $orderby = 'ASC';
		$sql = "SELECT * FROM {$this->tbp}member_grade WHERE status=1 {$where} ORDER BY sort ASC, id {$orderby}";
		$rs = $this->db->get_results($sql);
		success($rs);
	}

	//会员等级详情
	public function grade_detail() {
		$id = (isset($_GET['id']) && intval($_GET['id'])) ? intval($_GET['id']) : 0;
		if ($id<=0) error('缺少参数');
		$sql = "SELECT * FROM {$this->tbp}member_grade WHERE status=1 AND id='{$id}'";
		$row = $this->db->get_row($sql);
		if (!$row) error('该等级不存在');
		//获取当前等级的下个等级
		$score = 0;
		$sql = "SELECT score FROM {$this->tbp}member_grade WHERE status=1 AND id>'{$id}' ORDER BY sort ASC, id ASC";
		$next = $this->db->get_row($sql);
		if ($next) $score = intval($next->score);
		if ($score==0) {
			$sql = "SELECT score FROM {$this->tbp}member_grade WHERE id='{$id}'";
			$score = intval($this->db->get_var($sql));
		}
		$row->next_score = "{$score}";
		success($row);
	}

	//购买等级,通过购买手段来达成
	public function grade_order($is_show=true) {
		if ($this->member_id<=0) error('请登录', -100);
		$grade_id = (isset($_POST['grade_id']) && intval($_POST['grade_id'])) ? intval($_POST['grade_id']) : 0;
		$pay_method = (isset($_POST['pay_method']) && trim($_POST['pay_method'])) ? trim($_POST['pay_method']) : 'wxpay';
		if ($grade_id<=0) error('缺少参数');

		$sql = "SELECT score, price FROM {$this->tbp}member_grade WHERE status=1 AND id='{$grade_id}'";
		$row = $this->db->get_row($sql);
		if (!$row) error('该等级不存在');
		if ($this->member_score >= $row->score) error('您当前的会员等级已高于或等于该等级');

		$total_price = floatval($row->price);

		if ($pay_method=='yue') {
			if ($this->member_mod->is_yue_and_commission_enough($total_price)) {
				$status = 1;
				$pay_time = time();
			} else {
				error('您的佣金和余额不足以支付');
			}
		} else {
			$status = 0;
			$pay_time = 0;
		}

		$order_sn = 'DJ'.generate_order_sn();
		$sql = "INSERT INTO {$this->tbp}member_grade_order (member_id, grade_id, order_sn, total_price, pay_method, pay_time, status, add_time) VALUES
			('{$this->member_id}', '{$grade_id}', '{$order_sn}', '{$total_price}', '{$pay_method}', '{$pay_time}', '{$status}', '".time()."')";
		$this->db->query($sql);
		$order_id = $this->db->insert_id;

		//用余额支付，扣减余额和财富
		if ($pay_method == 'yue') {
			$sql = "SELECT score FROM {$this->tbp}member_grade WHERE id='{$grade_id}'";
			$score = intval($this->db->get_var($sql));
			$sql = "UPDATE {$this->tbp}member SET grade_id='{$grade_id}', grade_score='{$score}' WHERE id='{$this->member_id}'";
			$this->db->query($sql);
			//$this->member_mod->update_grade_from_score($this->member_id);
			$this->member_mod->pay_with_yue_and_commission($total_price, $order_id, 4);
		}

		$pay_method_name = '';
		switch ($pay_method) {
			case 'alipay':$pay_method_name = '支付宝支付';break;
			case 'wxpay':case 'wxpay_h5':$pay_method_name = '微信支付';break;
			case 'yue':$pay_method_name = '余额支付';break;
		}
		$_SESSION['order_sn'] = $order_sn;
		$_SESSION['total_price'] = $total_price;
		$_SESSION['pay_method_name'] = $pay_method_name;

		if ($is_show) {
			success(array("order_id"=>$order_id, "order_sn"=>$order_sn, "total_price"=>$total_price, "pay_method"=>$pay_method));
		}
	}

	//购买等级,微信端用,因为涉及到需要即时跳转去支付
	public function grade_pay() {
		//判断是否提交过来，如果是，表示是新订单，清空订单SESSION
		if (IS_POST) {
			$_SESSION['order_sn'] = '';
			$_SESSION['total_price'] = '';
			$_SESSION['pay_method_name'] = '';
		}
		$order_sn = (isset($_SESSION['order_sn']) && trim($_SESSION['order_sn'])) ? trim($_SESSION['order_sn']) : '';
		$total_price = (isset($_SESSION['total_price']) && floatval($_SESSION['total_price'])) ? floatval($_SESSION['total_price']) : 0;
		$pay_method_name = (isset($_SESSION['pay_method_name']) && trim($_SESSION['pay_method_name'])) ? trim($_SESSION['pay_method_name']) : '';
		$order_body = WEB_TITLE.' - 激活等级';
		if ($order_sn=='' || $total_price<=0) {
			$this->grade_order(false);
			$order_sn = (isset($_SESSION['order_sn']) && trim($_SESSION['order_sn'])) ? trim($_SESSION['order_sn']) : '';
			$total_price = (isset($_SESSION['total_price']) && floatval($_SESSION['total_price'])) ? floatval($_SESSION['total_price']) : 0;
			$pay_method_name = (isset($_SESSION['pay_method_name']) && trim($_SESSION['pay_method_name'])) ? trim($_SESSION['pay_method_name']) : '';
		}
		if ($order_sn=='' || $total_price<=0) {
			error('信息错误！');
		}

		//注释这两行，因为$pay_method_name从微信回调时是没有任何内容的;
		//by willson 2015-09-02
		//$_SESSION['pay_method_name'] = $pay_method_name;
		//$_SESSION['total_price'] = $total_price;
		/**
		 * JS_API支付demo
		 * ====================================================
		 * 在微信浏览器里面打开H5网页中执行JS调起支付。接口输入输出数据格式为JSON。
		 * 成功调起支付需要三个步骤：
		 * 步骤1：网页授权获取用户openid
		 * 步骤2：使用统一支付接口，获取prepay_id
		 * 步骤3：使用jsapi调起支付
		*/
		include_once(FRAMEWORK_PATH . "/class/wxapi/WxPayPubHelper/WxPayPubHelper.php");

		//使用jsapi接口
		$jsApi = new JsApi_pub();
		$openid = '';

		//=========步骤1：网页授权获取用户openid============
		//通过code获得openid
		$code = (isset($_GET['code']) && trim($_GET['code'])) ? trim($_GET['code']) : '';
		if (!$code){
			//触发微信返回code码
			$url = $jsApi->createOauthUrlForCode(urlencode(https().$_SERVER['SERVER_NAME']."/wap.php?app=member&act=grade_pay"));
			//echo $url;
			//exit;
			header("Location: {$url}");
			exit;
		}else{
			//获取code码，以获取openid
			//echo $code;
			//exit;
			$jsApi->setCode($code);
			$openid = $jsApi->getOpenid();
		}

		//=========步骤2：使用统一支付接口，获取prepay_id============
		//使用统一支付接口
		$unifiedOrder = new UnifiedOrder_pub();

		//设置统一支付接口参数
		//设置必填参数
		//appid已填,商户无需重复填写
		//mch_id已填,商户无需重复填写
		//noncestr已填,商户无需重复填写
		//spbill_create_ip已填,商户无需重复填写
		//sign已填,商户无需重复填写
		$unifiedOrder->setParameter("openid", "$openid");
		$unifiedOrder->setParameter("body", "$order_body");//商品描述
		if ($order_sn=='') {
			//自定义订单号，此处仅作举例
			$timeStamp = time();
			$order_sn = WxPayConf_pub::APPID."$timeStamp";
		}
		$unifiedOrder->setParameter("out_trade_no", "$order_sn");//商户订单号
		$unifiedOrder->setParameter("total_fee", $total_price*100);//总金额,单位:分
		$unifiedOrder->setParameter("notify_url", "http://".$_SERVER['SERVER_NAME']."/wx_notify_url.php");//通知地址
		$unifiedOrder->setParameter("trade_type", "JSAPI");//交易类型
		//非必填参数，商户可根据实际情况选填
		//$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号
		//$unifiedOrder->setParameter("device_info","XXXX");//设备号
		//$unifiedOrder->setParameter("attach","XXXX");//附加数据
		//$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
		//$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间
		//$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记
		//$unifiedOrder->setParameter("openid","XXXX");//用户标识
		//$unifiedOrder->setParameter("product_id","XXXX");//商品ID

		$prepay_id = $unifiedOrder->getPrepayId();
		//=========步骤3：使用jsapi调起支付============
		$jsApi->setPrepayId($prepay_id);

		$jsApiParameters = $jsApi->getParameters();
		//exit($jsApiParameters);
		success($jsApiParameters, '成功', 0, array("order_sn"=>$order_sn, "total_price"=>$total_price, "pay_method_name"=>$pay_method_name));
	}

	//等级支付成功
	public function grade_complete() {
		$order_sn = (isset($_GET['order_sn']) && trim($_GET['order_sn'])) ? trim($_GET['order_sn']) : '';
		if ($order_sn) {
			$_SESSION['order_sn'] = '';
			$_SESSION['total_price'] = '';
			$_SESSION['pay_method_name'] = '';
		}
		success('ok');
	}

    //定制报告
    public function report() {
		if ($this->member_id<=0) error('请登录');
		$sql = "SELECT * FROM {$this->tbp}diy WHERE member_id='{$this->member_id}' AND status>0 ORDER BY add_time DESC";
		$orders = $this->db->get_row($sql);
		if ($orders) {
			$sql = "SELECT * FROM {$this->tbp}diy_status WHERE diy_id='{$orders->id}' ORDER BY status DESC";
			$orders->status_list = $this->db->get_results($sql);
		}
        success($orders);
    }

    //商户
    public function business() {
		//获取会员所有信息
		$sql = "SELECT * FROM {$this->tbp}member WHERE id='{$this->member_id}'";
		$member = $this->db->get_row($sql);
		$_SESSION['member'] = $member;
        success('ok');
    }

    //合作
    public function operate_index(){
	    success('ok');
    }

    public function operate_ready(){
        success('ok');
    }

    public function operate_input(){
		if (IS_POST) {
			$name = (isset($_POST['name']) && trim($_POST['name'])) ? trim($_POST['name']) : '';
			$address = (isset($_POST['address']) && trim($_POST['address'])) ? trim($_POST['address']) : '';
			$idcard = (isset($_POST['idcard']) && trim($_POST['idcard'])) ? trim($_POST['idcard']) : '';
			$business_license = (isset($_POST['business_license']) && trim($_POST['business_license'])) ? trim($_POST['business_license']) : '';
			$sql = "SELECT count(*) FROM {$this->tbp}shop WHERE member_id='{$this->member_id}'";
			if ($this->db->get_var($sql)) error('你已经是商户了');
			$sql = "SELECT count(*) FROM {$this->tbp}shop_apply WHERE member_id='{$this->member_id}'";
			if ($this->db->get_var($sql)) error('请不要重复申请');

			$sql = "INSERT INTO {$this->tbp}shop_apply (member_id, name, address, idcard, business_license, add_time) VALUES
				('{$this->member_id}', '{$name}', '{$address}', '{$idcard}', '{$business_license}', '".time()."')";
			$this->db->query($sql);
			success('ok', '', '', '', 'wap.php?tpl=member.operate_complete');
		}

		$sql = "SELECT count(*) FROM {$this->tbp}shop WHERE member_id='{$this->member_id}'";
		if ($this->db->get_var($sql)) error('你已经是商户了');
		$sql = "SELECT count(*) FROM {$this->tbp}shop_apply WHERE member_id='{$this->member_id}'";
		if ($this->db->get_var($sql)) error('请不要重复申请');
        success('ok');
    }

    public function operate_input_upload(){
		if (IS_POST) {
			global $upyun_bucketname, $upyun_operator_name, $upyun_operator_pwd, $upyun_domain;
			$image_id = (isset($_POST['image_id']) && trim($_POST['image_id'])) ? trim($_POST['image_id']) : '';
			$pic = upload_one_file('pic', 'pic');
			if ($image_id!='') {
				//下载微信图片
				require_once(FRAMEWORK_PATH . '/class/wxapi/config.php');
				$wxapi = new wechatCallbackAPI();
				$json = $wxapi->access_token();
				$access_token = $json['access_token'];
				$url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$access_token}&media_id={$image_id}";
				$data = $wxapi->downloadFile($url);
				//$pic = upload_obj_file($data, 'avatar', 'body', false); //保存在本地
				$pic = upload_obj_file($data, 'avatar', 'body'); //上传到又拍云
				if (!$pic) error('图片上传失败');
			} else if (!$pic) {
				error('请选择图片');
			}
			$pic = add_domain($pic);
			success($pic);
		}
        error('数据错误');
    }

    //服务中心
    public function server() {
		$this->server_video();
    }

	//商品分类
	private function _categorys() {
		$sql = "SELECT id, name, pic FROM {$this->tbp}goods_category WHERE status='1' AND parent_id=0 ORDER BY sort ASC, id DESC";
		$rs = $this->db->get_results($sql);
		if ($rs) {
			$rs = add_domain_deep($rs, array("pic"));
		}
		return $rs;
	}

    public function server_video() {
		$offset = (isset($_GET['offset']) && trim($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && trim($_GET['pagesize'])) ? intval($_GET['pagesize']) : 8;
		$type = (isset($_GET['type']) && intval($_GET['type'])) ? intval($_GET['type']) : 1;
		$category_id = (isset($_GET['category_id']) && trim($_GET['category_id'])) ? intval($_GET['category_id']) : 0;
		$where = '';
		if ($category_id) $where = " AND category_id='{$category_id}'";
		$sql = "SELECT id, title, pic, memo FROM {$this->tbp}server WHERE type_id='{$type}' AND status=1 {$where} ORDER BY id DESC
			LIMIT {$offset}, {$pagesize}";
		$servers = $this->db->get_results($sql);
		$categorys = $type>1 ? $this->_categorys() : null;
        success(array('servers'=>$servers, 'categorys'=>$categorys));
	}

	//服务详情
    public function server_detail() {
		$id = (isset($_GET['id']) && trim($_GET['id'])) ? intval($_GET['id']) : 0;
		$sql = "SELECT *, '' as type_name FROM {$this->tbp}server WHERE id='{$id}' AND status=1";
		$row = $this->db->get_row($sql);
		if ($row) {
			if ($row->type_id==1) $row->type_name = '常见问题';
			else if ($row->type_id==2) $row->type_name = '视频教程';
			else if ($row->type_id==3) $row->type_name = '说明书';
		}
		success($row);
    }

    //申请减员
    public function person_reduce() {
        if (!$this->member_id) script('请先登录账号', 'wap.php?tpl=login');
	    //$rs = SQL::share('member_person')->where("member_id='{$this->member_id}' AND status=1")->sort('id DESC')->find();
        if (isMobile()){
            if (IS_POST) {
                $ids = $this->request->post('id');
                if (!strlen($ids)) error('请选择人员');
                SQL::share('person_reduce')->insert(array('member_id'=>$this->member_id, 'persons'=>$ids, 'add_time'=>time()));
                //SQL::share('member_person')->where("id IN (".implode(',',$ids).")")->update(array('status'=>0));
                success('ok');
            }
            $rs = SQL::share('collect c')
                ->left('member_person mp', 'c.idcard=mp.idcard')
                ->left('city cc', 'c.city_id=cc.city_id')
                ->where("mp.member_id='{$this->member_id}' AND mp.status=1")->sort('mp.id DESC')->find('mp.*, c.id, cc.name as city_name');
        }else{
            if (IS_POST) {
                $ids = $this->request->post('id');
                if (!strlen($ids)) error('请选择人员');
                SQL::share('person_reduce')->insert(array('member_id'=>$this->member_id, 'persons'=>$ids, 'add_time'=>time()));
                //SQL::share('member_person')->where("id IN (".implode(',',$ids).")")->update(array('status'=>0));
                script('申请减员成功', 'wap.php?app=member&act=person_reduce');
            }
            $rs = SQL::share('collect c')
                ->left('member_person mp', 'c.idcard=mp.idcard')
                ->left('city cc', 'c.city_id=cc.city_id')
                ->limit(0, 9)->isezr()
                ->where("mp.member_id='{$this->member_id}' AND mp.status=1")->sort('mp.id DESC')->find('mp.*, c.id, cc.name as city_name');
            $nav = '';
            if ($rs){
                $nav = $this->ezr->get_navigation();
            }
        }
        //增加PC需要的内容
        if (!isMobile()){
            //头像
            $sql = "SELECT avatar FROM {$this->tbp}member WHERE id='{$this->member_id}'";
            $avatar = $this->db->get_row($sql);
            //名称
            $sql = "SELECT nick_name FROM {$this->tbp}member WHERE id='{$this->member_id}'";
            $nick_name = $this->db->get_row($sql);
            // var_dump($rs);exit();
            success(array('rs'=>$rs, 'avatar'=>$avatar , 'nick_name'=>$nick_name, 'page'=>$nav));
        }else{
            success($rs);
        }
    }

    //我邀请的人
    public function invitation() {
        if (!$this->member_id) script('请先登录账号', 'wap.php?tpl=login');
        if (isMobile()){
            $rs = SQL::share('member_invitation')->where("member_id='{$this->member_id}'")->order('id DESC')->find();
        }else{
            $rs = SQL::share('member_invitation')->isezr()->limit(0, 10)->where("member_id='{$this->member_id}'")
                ->order('id DESC')->find();
            $nav = '';
            if ($rs){
                $nav = $this->ezr->get_navigation();
            }
        }

        if ($rs){
            foreach ($rs as $k => $g){
                $rs[$k]->avatar = SQL::share('member')->where("id='{$g->invitation_id}'")->val('avatar');
                $rs[$k]->nick_name = SQL::share('member')->where("id='{$g->invitation_id}'")->val('nick_name');
                $rs[$k]->add_time = date('Y-m-d', $g->add_time);

            }
        }

        //增加PC需要的内容
        if (!isMobile()){
            //头像
            $sql = "SELECT avatar FROM {$this->tbp}member WHERE id='{$this->member_id}'";
            $avatar = $this->db->get_row($sql);
            //名称
            $sql = "SELECT nick_name FROM {$this->tbp}member WHERE id='{$this->member_id}'";
            $nick_name = $this->db->get_row($sql);
           // var_dump($rs);exit();
            success(array('rs'=>$rs, 'avatar'=>$avatar , 'nick_name'=>$nick_name, 'page'=>$nav));
        }else{
            success($rs);
        }

    }


}
